package com.ptszyxx.popose.common.oos;


import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.ptszyxx.popose.MyApp;
import com.ysg.http.data.CommonRepository;
import com.ysg.http.data.entity.oos.OosTokenBean;
import com.ysg.utils.YFileUtil;
import com.ysg.base.BaseViewModel;
import com.ysg.http.BaseResponse;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.utils.YToastUtil;
import com.ysg.widget.pic.SelectPicBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class YOosUtil {
    public interface OnOosListener {
        void onSuccess(String url);
        void onSuccess(List<String> list);
        void onError();
    }

    private static YOosUtil instance;

    private YOosUtil(){
    }

    public static YOosUtil getInstance(){
        if (instance == null){
            synchronized (YOosUtil.class){
                if (instance == null){
                    instance = new YOosUtil();
                }
            }
        }
        return instance;
    }


    /**
     * 阿里云oosToken
     */
    public OosTokenBean tokenBean;
    public void getOosToken(CommonRepository repository, BaseViewModel viewModel) {
        tokenBean = null;
        Map<String, String> map = new HashMap<>();
        HttpUtils.getInstance()
                .data(repository.oosToken(map), viewModel,
                        new OnSuccessResult<OosTokenBean>() {
                            @Override
                            public void onSuccessResult(BaseResponse<OosTokenBean> response) {
                                tokenBean = response.getData();
                            }
                        });
    }

    public void upload(String path, String userId, boolean isSingle, OnOosListener listener) {
        if (tokenBean == null
                || tokenBean.getResponse() == null
                || tokenBean.getResponse().getCredentials() == null
        ){
            YToastUtil.showShort("oosToken为空");
            return;
        }
        OosTokenBean.Credentials credentials = tokenBean.getResponse().getCredentials();
        String endpoint = tokenBean.getEndpoint();
        String accessKeyId = credentials.getAccessKeyId();
        String accessKeySecret = credentials.getAccessKeySecret();
        String securityToken = credentials.getSecurityToken();

        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        OSSClient oss = new OSSClient(MyApp.getContext(), endpoint, credentialProvider);

//      image/android_uid_676_T_20230719091312.mp4
        String objectName = tokenBean.getKey() + "android_uid_" + userId + "_T_" + System.currentTimeMillis() + YFileUtil.getSuffix(path);
        Log.e("objectName", objectName);
        PutObjectRequest put = new PutObjectRequest(tokenBean.getBucketName(), objectName, path);
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("oos上传成功", "oos上传成功");
                if (listener != null){
                    if (isSingle){
                        listener.onSuccess(tokenBean.getUrl() + objectName);
                    }else{
                        urlList.add(tokenBean.getUrl() + objectName);
                        uploadIndex++;
                        if (uploadIndex == uploadSize){
                            listener.onSuccess(urlList);
                        }
                    }
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                clientException.printStackTrace();
                serviceException.printStackTrace();
                Log.d("上传失败", "上传失败");
                if (isSingle){
                    YToastUtil.showShort("oos上传失败");
                    if (listener != null){
                        listener.onError();
                    }
                }else{
                    uploadIndex++;
                    if (uploadIndex == uploadSize){
                        listener.onSuccess(urlList);
                    }
                }
            }
        });
        task.waitUntilFinished();
    }

    private int uploadIndex;
    private List<String> urlList = new ArrayList<>();
    private int uploadSize;
    public void upload(List<SelectPicBean> list, String userId, OnOosListener listener){
        uploadIndex = 0;
        urlList.clear();
        uploadSize = list.size();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < list.size(); i++){
                    SelectPicBean item = list.get(i);
                    upload(item.getPic(), userId, false, listener);
                }
            }
        }).start();

    }


}
